<script setup>
import { ref, onMounted, defineEmits } from 'vue';
import { postService } from "@/services/PostService.js";

const hotArticles = ref([]);
const isLoading = ref(true);
const hasError = ref(false);
const emits = defineEmits(['view-article']);

const viewArticle = (article) => {
  emits('view-article', article);
};

const fetchHotArticles = async () => {
  try {
    isLoading.value = true;
    hasError.value = false;
    hotArticles.value = await postService.getHotList();
  } catch (error) {
    console.error("获取热榜列表失败:", error);
    hasError.value = true;
  } finally {
    isLoading.value = false;
  }
};
onMounted(fetchHotArticles);
</script>

<template>
  <div class="hot-topics-container">
    <div class="hot-topics-header">
      <h3>24小时热榜</h3>
      <a href="#" class="more-link">更多 &gt;</a>
    </div>
    <div v-if="isLoading" class="state-info">正在加载...</div>
    <div v-else-if="hasError" class="state-info error">加载失败，请稍后重试</div>
    <ul v-else-if="hotArticles.length > 0" class="hot-topics-list">
      <li v-for="(article, index) in hotArticles" :key="article.id" class="topic-item" @click="viewArticle(article)">
        <span class="rank" :class="{ 'top-rank': index < 3 }">{{ index + 1 }}</span>
        <span class="topic-title">{{ article.title }}</span>
        <span class="topic-heat">{{ article.heat_score }} 🔥</span>
      </li>
    </ul>
    <div v-else class="state-info">暂无热门内容</div>
  </div>
</template>

<style scoped>
.state-info {
  color: #999;
  text-align: center;
  padding: 20px;
  font-size: 14px;
}
.state-info.error {
  color: #f56c6c;
}

.hot-topics-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16px;
  padding-bottom: 12px;
  border-bottom: 1px solid #f0f0f0;
}
.hot-topics-header h3 {
  margin: 0;
  color: #202124;
  font-size: 16px;
  font-weight: 500;
}
.hot-topics-header .more-link {
  font-size: 13px;
  color: var(--el-color-primary);
  text-decoration: none;
  font-weight: 500;
}
.hot-topics-list {
  list-style: none;
  padding: 0;
  margin: 0;
}
.topic-item {
  display: flex;
  align-items: center;
  padding: 10px 4px;
  border-radius: 6px;
  cursor: pointer;
  transition: background-color 0.2s ease;
}
.topic-item:hover {
  background-color: #f1f3f4;
}
.rank {
  width: 25px;
  text-align: center;
  font-weight: 500;
  margin-right: 12px;
  color: #5f6368;
}
.rank.top-rank {
  color: #d93025;
}
.topic-title {
  flex-grow: 1;
  color: #3c4043;
  font-size: 14px;
  line-height: 1.5;
}
.topic-heat {
  margin-left: 12px;
  color: #5f6368;
  font-size: 13px;
  flex-shrink: 0;
}
</style>